import { FlowNode } from '@/components/workflow/types'
import { useAvailableBlocks } from '@/pages/workflow/hooks/use-available-blocks'
import { MouseEvent, memo, useCallback, useState } from 'react'
import { Handle, Position } from 'reactflow'
import './index.less'

type NodeHandleProps = {
  handleId: string
  handleClassName?: string
  nodeSelectorClassName?: string
} & Pick<FlowNode, 'id' | 'data'>

export const NodeTargetHandle = memo(
  ({ id, data, handleId, handleClassName, nodeSelectorClassName }: NodeHandleProps) => {
    // console.log('==============NodeTargetHandle', id, data.type, data.isInIteration)
    const [open, setOpen] = useState(false)
    const connected = data._connectedTargetHandleIds?.includes(handleId)

    const { availablePrevBlocks } = useAvailableBlocks(data.type, data.isInIteration)
    const isConnectable = !!availablePrevBlocks.length

    const handleOpenChange = useCallback((v: boolean) => {
      setOpen(v)
    }, [])
    const handleHandleClick = useCallback(
      (e: MouseEvent) => {
        e.stopPropagation()
        if (!connected) setOpen(v => !v)
      },
      [connected]
    )

    return (
      <>
        <Handle
          id={handleId}
          type="target"
          position={Position.Left}
          className={`
          custom-workflow-handle-point absolute z-[1] ml-[-3px] h-[13px] w-[13px] rounded-full bg-[#9197f1]
          transition-all
          hover:scale-125 hover:bg-[#4d53e8]
          ${handleClassName}
        `}
          isConnectable={isConnectable}
          onClick={handleHandleClick}
        ></Handle>
      </>
    )
  }
)
NodeTargetHandle.displayName = 'NodeTargetHandle'

export const NodeSourceHandle = memo(
  ({ id, data, handleId, handleClassName, nodeSelectorClassName }: NodeHandleProps) => {
    // console.log('==============NodeSourceHandle', id, data.type, data.isInIteration)
    const [open, setOpen] = useState(false)

    const { availableNextBlocks } = useAvailableBlocks(data.type, data.isInIteration)
    const isConnectable = !!availableNextBlocks.length

    const connected = data._connectedSourceHandleIds?.includes(handleId)
    const handleOpenChange = useCallback((v: boolean) => {
      setOpen(v)
    }, [])
    const handleHandleClick = useCallback(
      (e: MouseEvent) => {
        e.stopPropagation()
        if (!connected) setOpen(v => !v)
      },
      [connected]
    )

    return (
      <>
        <Handle
          id={handleId}
          type="source"
          position={Position.Right}
          className={`
          custom-workflow-handle-point absolute z-[1] mr-[-3px] h-[13px] w-[13px] rounded-full bg-[#9197f1]
          transition-all
          hover:scale-125 hover:bg-[#4d53e8]
          ${handleClassName}
        `}
          isConnectable={isConnectable}
          onClick={handleHandleClick}
        ></Handle>
      </>
    )
  }
)
NodeSourceHandle.displayName = 'NodeSourceHandle'
